package netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @author zhangjunfei
 * @date 2021/12/10 11:43
 */
public class HelloWorldClient {

    private int port;
    private String address;

    public HelloWorldClient(int port, String address) {
        this.port = port;
        this.address = address;
    }

    public HelloWorldClient() {
    }

    public void start(){
        EventLoopGroup loopGroup = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();


        bootstrap.group(loopGroup)
                .channel(NioSocketChannel.class)
                .handler(new ClientChannelInitializer());


        try {
            Channel channel = bootstrap.connect(address, port).sync().channel();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            for (; ; ) {
                String s = bufferedReader.readLine();
                if (s == null) {
                    continue;
                }
                channel.writeAndFlush(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            loopGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        HelloWorldClient helloWorldClient = new HelloWorldClient(7788, "127.0.0.1");
        helloWorldClient.start();
    }

}
